<script setup lang="ts">
import { formatTimeRemaining } from '@renderer/utils'
import { onMounted, reactive, ref, onBeforeUnmount } from 'vue'

const time = reactive<{
  hour: number
  minute: number
  second: number
}>({
  hour: 0,
  minute: 2,
  second: 0
})

const timeRemaining = ref<number>(0)

const isBeginDown = ref<NodeJS.Timeout>()

const countDownStr = ref<string[] | number[]>([])

const countdown = () => {
  timeRemaining.value = computedTime(time)
  beginDown()
  isBeginDown.value = setInterval(beginDown, 1000)
}

const computedTime = ({ hour, minute, second }): number =>
  (hour * 3600 + minute * 60 + second) * 1000

const beginDown = () => {
  timeformat(timeRemaining.value)
  timeRemaining.value -= 1000
}

const timeformat = (timeNumber: number) => {
  const { seconds, minutes, hours } = formatTimeRemaining(timeNumber)

  // ${days > -1 ? `${days.toString().padStart(2, '0')}:` : ''}

  countDownStr.value = `${hours > -1 ? `${hours.toString().padStart(2, '0')}:` : ''}${
    minutes > -1 ? `${minutes.toString().padStart(2, '0')}:` : ''
  }${seconds > -1 ? `${seconds.toString().padStart(2, '0')}` : ''}`.split(':')

  if (timeRemaining.value === 0) {
    clearInterval(isBeginDown.value)
  }
}
onMounted(countdown)

onBeforeUnmount(() => {
  clearInterval(isBeginDown.value)
})
</script>
<template>
  <div class="countdown w-full h-full flex items-center justify-center text-white">
    <section class="flex gap-1">
      <template v-for="(item, index) in countDownStr" :key="index">
        <span
          v-for="timeItem in item"
          :key="timeItem"
          class="flex flex-row items-center justify-center bg-white text-black p-[2px] rounded-md overflow-hidden w-max"
        >
          {{ timeItem }} </span
        ><span v-if="index < countDownStr?.length - 1" class="colon">:</span>
      </template>
    </section>
  </div>
</template>
<style lang="scss" scoped>
.countdown {
  font-family: 'Cc';
  section {
    font-size: 30px;
    .colon {
      background-image: linear-gradient(120deg, #a1c4fd 0%, #c2e9fb 100%);
      background-clip: text;
      -webkit-background-clip: text;
      color: transparent;
    }
  }
}
</style>
